package com.example.lt.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.lt.entity.queryPage.BasePage;
import com.example.lt.entity.user.Role;
import com.example.lt.entity.user.User;
import com.example.lt.entity.user.UserRole;
import com.example.lt.service.user.RoleService;
import com.example.lt.service.user.UserRoleService;
import com.example.lt.service.user.UserService;
import com.example.lt.util.Result;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author 小涛Tao
 * @Date: 2024/08/20/18:26
 * version 1.0 注释：管理端用户控制器
 **/
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/admin/user")
public class AdminUserController {

    private final UserService userService;

    private final UserRoleService userRoleService;

    private final RoleService roleService;


    /**
     * 获取用户列表
     * @return
     */
    @GetMapping("/page")
    public Result list() {
        log.info("获取用户列表");
        return Result.ok().data(userService.list(new LambdaQueryWrapper<>()));
    }

    /**
     * 获取用户列表，包括拥有的角色身份
     * @param basePage
     * @param userName
     * @return
     */
    @GetMapping("/list")
    public Result list(BasePage basePage, @RequestParam(required = false) String userName) {
        log.info("获取用户列表，包括拥有的角色身份");
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(!ObjectUtils.isEmpty(userName), User::getNickName, userName);
        IPage<User> page = userService.page(basePage.page(), wrapper);

        Map<Long, List<UserRole>> userRoleMap = userRoleService.list(null)
                .stream().collect(Collectors.groupingBy(UserRole::getUserId));

        Map<Long, String> roleMap = roleService.list(null)
                .stream().collect(Collectors.toMap(Role::getId, Role::getName));

        HashMap<Long, Set<String>> map = new HashMap<>();

        userRoleMap.forEach((uId, userRoles) -> {
            final Set<String> roles = new HashSet<>();
            for (UserRole userRole : userRoles) {
                roles.add(roleMap.get(userRole.getRoleId()));
            }
            map.put(uId, roles);
        });
        for (User user : page.getRecords()) {
            user.setRoleName(map.get(user.getId()));
        }

        return Result.ok().data(page.getRecords()).count(page.getTotal());
    }

}
